package com.scs.application.interceptor;

import com.scs.application.consts.GlobalConsts;
import com.scs.application.core.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 */
@Slf4j
@Component
public class ChannelFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        ServletRequest requestWrappercustom = null;
        if(servletRequest instanceof HttpServletRequest) {
            // EG: tool/uploadImg
            String servletPath = ((HttpServletRequest) servletRequest).getServletPath();
            if (
                    StringUtils.isNotBlank(servletPath)
                            && (
                            GlobalConsts.CHANNEL_FILTER_EXCLUDE.contains(servletPath)
                                    ||
                                    GlobalConsts.CHANNEL_FILTER_EXCLUDE.stream().filter(item -> servletPath.indexOf(item) != -1).findFirst().isPresent()
                    )
            ){
                filterChain.doFilter(servletRequest, servletResponse);
                return;
            }
            requestWrappercustom = new RequestWrapper((HttpServletRequest) servletRequest);
        }
        if(requestWrappercustom == null) {
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            filterChain.doFilter(requestWrappercustom, servletResponse);
        }
    }
}
